import {Icon, Input, Tree} from 'antd';
// import Icon from '../../_antd1.11.2/icon'
// import Input from '../../_antd1.11.2/input'
// import Tree from '../../_antd1.11.2/tree'
const TreeNode = Tree.TreeNode;

const getFd = (values) => {
    let fd = "";
    //var data = new FormData();
    for(let p in values) {
        fd += p+"="+values[p]+"&";
        //data.append(p,values[p]);
    }
    return fd;
}

function getTreeDatas(url,params) {
    return new Promise(function(resolve) {
        //console.log("jQuery:",jQuery);
        //console.log("$:",$);
        fetch(url,{
            method: 'post',
            headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'},
            credentials: 'include',
            body: params
            //body: JSON.stringify(data)
        }).then(function(response) {
            //console.log("data:",data);
            //console.log("response.json():",response);
            resolve(response.json());
        }).catch(function(ex) {
            resolve([]);
            console.log('parsing failed', ex)
        });
        // jQuery.ajax({
        //     type:"POST",
        //     url:url,
        //     data:params,
        //     success(datas) {
        //         resolve(datas);
        //     },
        //     error(datas) {
        //         resolve([]);
        //     },
        //     dataType: "json"
        // });
    });
}

let that = {};

class WeaTree extends React.Component {
    constructor(props) {
        super(props);
        const {dataUrl,otherPara,prefix,topPrefix,dataKey,isMult,ids,names} = props;
        let url = dataUrl;//+"?"+otherPara[0]+"="+otherPara[1];
        for(let i=0;i<otherPara.length;i+=2) {
            if(i==0) url += "?";
            else url += "&";
            url += otherPara[i]+"="+otherPara[i+1];
        }
        let idArr = ids?ids.split(","):[];
        let nameArr = names?names.split(","):[];
         for(let i=0;i<idArr.length;i++) {
            idArr[i] = prefix+idArr[i];
        }
        //console.log("idArr:",idArr);
        this.state = {
            treeData: [],
            url:url,
            prefix:prefix,
            dataKey:dataKey,
            topPrefix:topPrefix,
            isMult:isMult,
            ids:idArr,
            names:nameArr
        }
        that = this;
    }
    componentDidMount() {
        let that = this;
        const {url,dataKey,topPrefix} = this.state;
        const params = dataKey+"="+topPrefix+"0";
        //console.log("params:",params);
        getTreeDatas(url,params).then(function(datas) {
            //console.log("componentDidMount2:",datas);
            that.setState({
                treeData:generateTreeNodes(datas,null)
            });
        });
    }
    componentWillReceiveProps(nextProps) {
        const {ids,names,prefix} = this.props;
        const nextIds = nextProps.ids;
        const nextNames = nextProps.names;
        //console.log("ids1:",ids);
        //console.log("nextIds1:",nextIds);
        if(ids!=nextIds) {
            let idArr = nextIds?nextIds.split(","):[];
            let nameArr = nextNames?nextNames.split(","):[];
            for(let i=0;i<idArr.length;i++) {
                idArr[i] = prefix+idArr[i];
            }
            this.setState({
                ids:idArr,
                names:nameArr
            });
        }
    }
    onSelect(info,e) {
        //console.log('info', info);
        //console.log("e1:",e);
        const {isMult} = this.state;
        if(!isMult) {
            const nodes = e.selectedNodes;
            const nowNode = e.node;
            this.setTheDatas(nodes,nowNode);
        }
        else {
            let {ids,names,prefix} = this.state;
            let newIds = [];
            let newNames = [];
            const nowNode = e.node;
            //console.log("nowNode.props.selected:",nowNode.props.selected);
            if(nowNode.props.selected) { //选中时
                for(let i=0;i<ids.length;i++) {
                    //console.log(ids[i]+"!="+nowNode.props.id);
                    if(ids[i]!=nowNode.props.id) {
                        newIds.push(ids[i].substring(prefix.length));
                        newNames.push(names[i]);
                    }
                }
            }
            else { //取消时
                let find = false;
                for(let i=0;i<ids.length&&!find;i++) {
                    //console.log(ids[i]+"!="+nowNode.props.id);
                    if(ids[i]==nowNode.props.id) {
                        find = true;
                    }
                    newIds.push(ids[i].substring(prefix.length));
                    newNames.push(names[i]);
                }
                if(!find&&nowNode.props.id.indexOf(prefix)==0) {
                    newIds.push(nowNode.props.id.substring(prefix.length));
                    newNames.push(nowNode.props.name);
                }
            }
            //console.log("newIds:",newIds);
            this.props.setData(newIds.join(","),newNames.join(","));
            for(let i=0;i<newIds.length;i++) {
                newIds[i] = prefix+newIds[i];
            }
            //console.log("newIds1:",newIds);
            //console.log("newNames:",newNames);
            this.setState({
                ids:newIds,
                names:newNames
            });
        }
    }
    onCheck(info,e) {
        //console.log("is in onCheck :",e);
        //console.log('info', info);
        //console.log("e2:",e);
        const {isMult} = this.state;
        if(isMult) {
            //console.log("e:",e);
            const nodes = e.checkedNodes;
            const nowNode = e.node;
            this.setTheDatas(nodes,nowNode);
        }
    }
    setTheDatas(nodes,nowNode) {
        let idArr = [];
        let nameArr = [];
        const {prefix} = this.state;
        for(let i=0;i<nodes.length;i++) {
            const node = nodes[i].props;
            //console.log("node1:",node);
            //console.log("idArr",idArr);
            //console.log("node.id:",node.id);
            //console.log(idArr.indexOf(node.id)<0);
            if(node.id.indexOf(prefix)==0&&idArr.indexOf(node.id.substring(prefix.length))<0) {
                idArr.push(node.id.substring(prefix.length));
                nameArr.push(node.name);
            }
        }
        let ids = idArr.join(",");
        let names = nameArr.join(",");
        this.props.setData(ids,names);
        for(let i=0;i<idArr.length;i++) {
            idArr[i] = prefix+idArr[i];
        }
        this.setState({
            ids:idArr,
            names:nameArr
        });
    }
    onLoadData(treeNode) {
        let that = this;
        const {url,dataKey} = that.state;
        //console.log("treeNode1:",treeNode);
        const {eventKey,treeKey} = treeNode.props;
        const params = dataKey+"="+eventKey;
        return new Promise(function(resolve) {
             getTreeDatas(url,params).then(function(datas) {
                const treeData = [...that.state.treeData];
                getNewTreeData(treeData, treeKey, generateTreeNodes(datas,treeNode), 2);
                //console.log("treeData:",treeData);
                that.setState({treeData});
                resolve();
            });
        });

        /*
        return new Promise((resolve) => {
            setTimeout(() => {
                const treeData = [...this.state.treeData];
                getNewTreeData(treeData, treeNode.props.eventKey, generateTreeNodes(treeNode), 2);
                this.setState({ treeData });
                resolve();
            }, 500);
        });
        */
    }
    render() {
        const {isMult,ids} = this.state;
        const loop = data => data.map((item) => {
            let title = item.isTheData?(<div> <img style= {{'vertical-align':'-13%'}} src="/cloudstore/images/store/subCopany_Colse_wev8.gif"/> {item.name}</div>):(<div><img style= {{'vertical-align':'sub'}} src="/cloudstore/images/store/Home_wev8.gif"/>{item.name}</div>);
            if (item.children) {
                return <TreeNode title={title} name={item.name} key={item.key} id={item.key} treeKey={item.treeKey}>{loop(item.children)}</TreeNode>
            }
            return <TreeNode title={title} name={item.name} key={item.key} id={item.key} treeKey={item.treeKey} isLeaf={item.isLeaf} />
        });
        const treeNodes = loop(this.state.treeData);
//        console.log("treeNodes:",treeNodes);
        //console.log("treeNodes:",treeNodes);
        //let checkKeys = ids.length==0?undefined:ids;
        //console.log("checkKeys:",checkKeys);
        //selectedKeys={ids} checkedKeys={ids}
        //console.log("ids:",ids);
        //checkStrictly={true}
        return (
            <Tree className="my-Tree" onSelect={this.onSelect.bind(this)} onCheck={this.onCheck.bind(this)} loadData={this.onLoadData.bind(this)} checkable={isMult} multiple={isMult} selectedKeys={ids} checkedKeys={ids} >
            {treeNodes}
            </Tree>
        )
    }
};

function generateTreeNodes(datas,treeNode) {
    //console.log("treeNode init 1:",treeNode);
    let arr = new Array();
    //,dataKey,topPrefix
    const {topPrefix,prefix} = that.state;
    for (let i=0;i<datas.length;i++) {
        const data = datas[i];
        if(treeNode) {
            const {treeKey,id} = treeNode.props;
            arr.push({
                name: data.name,
                //key:`${treeKey}-${data.id}`,
                key:data.id,
                treeKey:`${treeKey}-${data.id}`,
                isLeaf:data.isParent!="true",
                isTheData:data.id.indexOf(prefix)==0
            });
        }
        else {
            arr.push({
                name: data.name,
                //key:`${topPrefix}0-${data.id}`,
                key:data.id,
                treeKey:`${topPrefix}0-${data.id}`,
                isLeaf:data.isParent!="true",
                isTheData:data.id.indexOf(prefix)==0
            });
        }
        //console.log("arr:",arr[i]," data:",data," data.isParent!=true:",data.isParent!="true");
        //arr.push({ name: `leaf ${key}-${i}`, key: `${key}-${i}` });
    }
    //console.log("arr : ",arr);
    //datas = arr;
    return arr;
}

function setLeaf(treeData, curKey, level) {
    const loopLeaf = (data, lev) => {
        const l = lev - 1;
        data.forEach((item) => {
            if ((item.treeKey.length > curKey.length) ? item.treeKey.indexOf(curKey) !== 0 :curKey.indexOf(item.treeKey) !== 0) {
                return;
            }
            if (item.children) {
                loopLeaf(item.children, l);
            } else if (l < 1) {
                //item.isLeaf = true;
            }
        });
    };
    loopLeaf(treeData, level + 1);
}

function getNewTreeData(treeData, curKey, child, level) {
    //console.log("ok");
    const loop = (data) => {
        //if (level < 1 || curKey.length - 3 > level * 2) return;
        data.forEach((item) => {
            //console.log((curKey+"-")+".indexOf("+item.treeKey+")==="+(curKey+"-").indexOf(item.treeKey+"-"));
            //console.log(curKey.indexOf(item.treeKey) === 0);
            if ((curKey+"-").indexOf(item.treeKey+"-") === 0) {
            //if (curKey.indexOf(item.treeKey) === 0) {
                if (item.children) {
                    loop(item.children);
                } else {
                    item.children = child;
                }
            }
        });
    };
    loop(treeData);
    setLeaf(treeData, curKey, level);
}

export default WeaTree;










/* //backup


import { Tree } from 'antd';
const TreeNode = Tree.TreeNode;

function generateTreeNodes(treeNode) {
    const arr = [];
    const key = treeNode.props.eventKey;

    for (let i = 0; i < 3; i++) {
        arr.push({ name: `leaf ${key}-${i}`, key: `${key}-${i}` });
    }
    return arr;
}

function setLeaf(treeData, curKey, level) {
    const loopLeaf = (data, lev) => {
        const l = lev - 1;
        data.forEach((item) => {
            if ((item.key.length > curKey.length) ? item.key.indexOf(curKey) !== 0 :
                curKey.indexOf(item.key) !== 0) {
                return;
            }
            if (item.children) {
                loopLeaf(item.children, l);
            } else if (l < 1) {
                item.isLeaf = true;
            }
        });
    };
    loopLeaf(treeData, level + 1);
}

function getNewTreeData(treeData, curKey, child, level) {
    const loop = (data) => {
        if (level < 1 || curKey.length - 3 > level * 2) return;
        data.forEach((item) => {
            if (curKey.indexOf(item.key) === 0) {
                if (item.children) {
                    loop(item.children);
                } else {
                    item.children = child;
                }
            }
        });
    };
    loop(treeData);
    setLeaf(treeData, curKey, level);
}

class WeaTree extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            treeData: []
        }
    }
    componentDidMount() {
        setTimeout(() => {
            this.setState({
                treeData: [
                { name: 'pNode 01', key: '0-0' },
                { name: 'pNode 02', key: '0-1' },
                { name: 'pNode 03', key: '0-2', isLeaf: true },
                ],
            });
        }, 100);
    }
    onSelect(info) {
        console.log('selected', info);
    }
    onLoadData(treeNode) {
        return new Promise((resolve) => {
            setTimeout(() => {
                const treeData = [...this.state.treeData];
                getNewTreeData(treeData, treeNode.props.eventKey, generateTreeNodes(treeNode), 2);
                this.setState({ treeData });
                resolve();
            }, 500);
        });
    }
    render() {
        const loop = data => data.map((item) => {
            if (item.children) {
                return <TreeNode title={item.name} key={item.key}>{loop(item.children)}</TreeNode>
            }
            return <TreeNode title={item.name} key={item.key} isLeaf={item.isLeaf} disabled={item.key === '0-0-0'} />
        });
        const treeNodes = loop(this.state.treeData);
        return (
            <Tree onSelect={this.onSelect.bind(this)} loadData={this.onLoadData.bind(this)}>
            {treeNodes}
            </Tree>
        )
    }
};

export default WeaTree;
*/